<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "" : request.getParameter("isShow");
	String xm_id = request.getParameter("xm_id") == null ? "" : request.getParameter("xm_id");
	String xm_code = request.getParameter("xm_code") == null ? "" : request.getParameter("xm_code");
	String xm_name = request.getParameter("xm_name") == null ? "" : request.getParameter("xm_name");
	String customer_id = request.getParameter("customer_id") == null ? "" : request.getParameter("customer_id");
	String customer = request.getParameter("customer") == null ? "" : request.getParameter("customer");
	String dept_id = request.getParameter("dept_id") == null ? "" : request.getParameter("dept_id");
	String dept_name = request.getParameter("dept_name") == null ? "" : request.getParameter("dept_name");
	String id = request.getParameter("id") == null ? "" : request.getParameter("id");
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	boolean isAdd = "".equals(id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }
%>
<html>
	<head>
		<title><%=isAdd?"新建项目支付":"编辑项目支付" %></title>
		<script type="text/javascript" src="<%=contextPath %>/public/js/extend.js"></script>
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
		</style>
	<script type="text/javascript">
		var lastIndex;
		var lastIndex1;
		var xm_id="<%=xm_id%>"; 
		var id="<%=id%>";
		var supply_id;
		var isInit=0;
		$(function(){
			$('#pay_value').numberbox('disable',true);
			if('<%=flag%>' == 1){
					jQuery('#ff').form({
						onLoadSuccess:function(){
						 $("#worker").combogrid("setValue",jQuery("#pay_to_id").val());
					 	 $("#worker").combogrid("setText",jQuery("#pay_to_name").val());
					 	 $("#worker").combogrid("disable",true);
						}
					});
				 $('#ff').form('load','<%=contextPath %>/springMVC/xmFinance/viewXmPay?id=<%=id%>');
			}
			var url='<%=contextPath %>/springMVC/xmFinance/listXMWorkers';
			var urlAdv="";
			$("#worker").combogrid({
				title:'选择客户',
				panelWidth:550,
				panelHeight:400,
				url:url,
				idField:"gd_worker_id",
				textField:"gd_worker_name",
				rownumbers:true,
				fitColumns:true,
				onBeforeLoad:function(param){
					param.xm_id=xm_id;
				},
				onChange:function(){
					$("#table").datagrid("reload");
					$("#tableAdv").datagrid("reload");
				},
			    onSelect: function (rowIndex, rowData){  
					jQuery("#loan_money").numberbox("setValue",rowData.loan_money);
			        }, 
				columns: [[
					{field:'gd_worker_id',hidden:true},
					{field:'gd_worker_name',title:'施工队',width:100,align:'center'},
					{field:'gd_worker_person',title:'负责人',width:100,align:'center'},
					{field:'loan_money',title:'借款金额',width:100,align:'center'}
				]],
				toolbar:'#tb'
			});
			
			jQuery("#tableAdv").datagrid({
				title:"扣班组垫款",
				iconCls:'icon-receive',
				loadMsg:'正在加载数据，请稍后......',
				<%=isAdd?"url:'"+contextPath+"/springMVC/gd/listGdYetAdvance',":"url:'"+contextPath+"/springMVC/gd/listGdYetAdvancesByYetId?id="+id+"',"%>
				rownumbers:true,
				fitColumns:true,
				idField:'id',
				frozenColumns:[[
				      //{field:'ck',checkbox:true},
				      {title:'主键',field:'id',hidden:true}
				]],
				columns:[[
						{title:'工单id',field:'gd_id',hidden:true},
						{title:'工单编号',field:'gd_code',width:250,align:'center'},
						{title:'工单名称',field:'gd_name',width:150,align:'center'},
						{title:'垫款标题',field:'title',width:100,align:'center'},
						{title:'金额',field:'money',width:100,align:'center'},
						{title:'本金',field:'now_on_money',width:100,align:'center'},
						{title:'利率',field:'rate',width:100,align:'center'},
						{title:'利息',field:'lxMoney',width:100,align:'center',formatter:function(value,rowData,rowIndex){
							return rowData.lxMoney=jsRate(rowData);
						}},
						{title:'已还金额',field:'already_money',width:100,align:'center'},
						{title:'本次还款金额',field:'yet_money',width:100,align:'center',editor:{
							type:'numberbox',
							options:{
								min:0,
								precision:2
							}
						},formatter:function(value,rowData,rowIndex){
							if(value == undefined){
							return rowData.yet_money=parseFloat(rowData.now_on_money)+parseFloat(rowData.lxMoney);
							}
							return rowData.yet_money;
						}}
					
				]],
				onBeforeLoad:function(param){
					var pay_to_id = $("#worker").combogrid("getValue");
					param.xm_id=xm_id;
					param.id=id;
					param.worker_id=pay_to_id;
					$(this).datagrid('rejectChanges');
					
				},
				onAfterEdit:function(rowIndex, rowData, changes){
					advancesMoney();
					calculaMoney();	
				},
				onClickCell:function(rowIndex,field,value){
					if (lastIndex1 != rowIndex){
						$('#tableAdv').datagrid('endEdit', lastIndex1);
						$('#tableAdv').datagrid('beginEdit', rowIndex);
						var ed = $('#tableAdv').datagrid('getEditor', {index:rowIndex,field:field});
						if(ed == null){
							ed = $('#tableAdv').datagrid('getEditor', {index:rowIndex,field:'yet_money'});
						}
						$(ed.target).select();
					}
					lastIndex1 = rowIndex;
				},
				onLoadSuccess:function(rtJson){
					calculaMoney();
				},
				toolbar:[
							{
							id:'save',
							text:'保存修改',
							disabled:false,
							iconCls:'icon-save',
							handler:function(){
								$('#tableAdv').datagrid('acceptChanges');
								lastIndex1 =-1;
								calculaMoney();	
								//advancesMoney()
							}
							}],
				pageSize:10,
				pageList : [10,50,100],  
				pagination:true,
				onLoadSuccess:function(rtJson){
					if(rtJson.rtState== '1')
					{
						$.messager.alert('提示',rtJson.rtMsrg);
					}
				}
			});
			
			
			
	       $('#table').datagrid({
	    	  	 title:"支付班组",
				 iconCls:'icon-zc',
				 url:'<%=contextPath %>/springMVC/xmFinance/listFBEndPayByXMIdAndWorkerId',
	    	     rownumbers:true,
				fitColumns:true,
				frozenColumns:[[
					{field:'ck',checkbox:true},
				    {title:'工单支付id',field:'bus_id',hidden:true}
				]],				
				columns:[[
					{title:'工单id',field:'gd_id',hidden:true},
					{title:'分包id',field:'gd_worker_id',hidden:true},
					{title:'分包商',field:'gd_worker_name',width:250,align:'center'},
					{title:'工单编号',field:'gd_code',width:250,align:'center'},
					{title:'工单名称',field:'gd_name',width:150,align:'center'},					
					{title:'实际结算支付',field:'end_pay',width:200,align:'center',formatter:function(value,rowData,index){
						if(isNaN(rowData.worker_pay)){
							rowData.worker_pay=0;
						}
						if(isNaN(rowData.already_pay)){
							rowData.already_pay=0;
						}
						if(isNaN(rowData.new_borrow_pay)){
							rowData.new_borrow_pay=0;
						}						
						if(isNaN(rowData.interest)){
							rowData.interest=0;
						}
						if(isNaN(rowData.cut_payment)){
							rowData.cut_payment=0;
						}													
					
					
					//rowData.end_pay=parseFloat(rowData.worker_pay)-parseFloat(rowData.already_pay)-parseFloat(rowData.borrow_pay)-parseFloat(rowData.interest)-parseFloat(rowData.cut_payment);
					rowData.end_pay=parseFloat(rowData.worker_pay)-parseFloat(rowData.already_pay)-parseFloat(rowData.cut_payment);
					return rowData.end_pay;
					}},
					{title:'结算已付',field:'abpay',width:200,align:'center',formatter:function(value,rowData,index){
						if(isNaN(rowData.abpay)){
							rowData.abpay=0;
						}
						
					return rowData.abpay;
					}},		
					{title:'垫款金+息',field:'viewB',width:200,align:'center',formatter:function(value,rowData,index){
						if(isNaN(rowData.new_borrow_pay)){
							rowData.new_borrow_pay=0;
						}
						if(isNaN(rowData.newInterest)){
							rowData.newInterest=0;
						}

					rowData.viewB=parseFloat(rowData.new_borrow_pay)+parseFloat(rowData.newInterest);
					return rowData.viewB;
					}},	
											
					{title:'本次支付款',field:'end_now_pay',width:200,align:'center',editor:{
						type:'numberbox',
						options:{
							precision:2
						}
					},formatter:function(value,rowData,index){
					if(value == undefined){
						rowData.end_now_pay=parseFloat(rowData.end_pay)-parseFloat(rowData.abpay)-parseFloat(rowData.viewB);
						rowData.end_now_pay=Math.round(rowData.end_now_pay*100)/100;
					}
					return rowData.end_now_pay;
					}},								
					{title:'备注',field:'remark',width:200,align:'center',editor:{
						type:'textarea'
					}}
				]],
				onBeforeLoad:function(param){
					param.xm_id=xm_id;
					param.worker_id=$("#worker").combogrid("getValue");
					param.xmPayId=id;
					$(this).datagrid('rejectChanges');
				},
				onAfterEdit:function(rowIndex, rowData, changes){
				calculaMoney();
				},
				onClickCell:function(rowIndex,field,value){
					if (lastIndex != rowIndex){
						$('#table').datagrid('endEdit', lastIndex);
						$('#table').datagrid('beginEdit', rowIndex);
						var ed = $('#table').datagrid('getEditor', {index:rowIndex,field:field});
						if(ed == null){
							ed = $('#table').datagrid('getEditor', {index:rowIndex,field:'end_now_pay'});
						}
						$(ed.target).select();
					}
					lastIndex = rowIndex;
				},
				onLoadSuccess:function(rtJson){
					calculaMoney();
				},
				toolbar:[
					{
					id:'save',
					text:'保存修改',
					disabled:false,
					iconCls:'icon-save',
					handler:function(){
						$('#table').datagrid('acceptChanges');
						lastIndex =-1;
						calculaMoney();	
	
					}
					},'-',{
					id:'delete',
					text:'删除',
					disabled:false,
					iconCls:'icon-remove',
					handler:function(){
						$('#table').datagrid('acceptChanges');
						lastIndex =-1;
						var rows = $('#table').datagrid('getSelections');
						if (rows.length > 0){
							for(var i=0;i<rows.length;i++){
								var row = rows[i];
								var index = $('#table').datagrid('getRowIndex', row);
								$('#table').datagrid('deleteRow', index);
							}
						}
						var data = $('#table').datagrid('getData');
						$('#table').datagrid('loadData',data);
					}
				}
			   ]
			});
			
		});
		function calculaMoney(){
				var inMoneys=0;
				var jsondata=$("#table").datagrid("getData");
				for(var i=0;i<jsondata.total;i++){
				if(isNaN(jsondata.rows[i].end_now_pay)){
							jsondata.rows[i].end_now_pay=0;
						}	
				inMoneys+=parseFloat(jsondata.rows[i].end_now_pay);	
				
				}
				var jsondata2=$("#tableAdv").datagrid("getData");
				for(var i=0;i<jsondata2.total;i++){
						if(isNaN(jsondata2.rows[i].yet_money)){
							jsondata2.rows[i].yet_money=0;
						}
				inMoneys+=parseFloat(jsondata2.rows[i].yet_money);	
				
				}
				jQuery("#payValue").numberbox('setValue', inMoneys);
				var loan_money=jQuery("#loan_money").numberbox("getValue");
				$('#pay_value').numberbox('setValue', inMoneys-loan_money);
		}	
		function addPayValue(){
				calculaMoney();					
		}
		function addRow(){
			$('#table').datagrid('endEdit', lastIndex);
			$('#table').datagrid('appendRow',{
				top:'1000',
				low:'0',
				num:'0'
			});
			var data = $('#table').datagrid('getData');
			$('#table').datagrid('loadData',data);
			lastIndex = $('#table').datagrid('getRows').length-1;
			$('#table').datagrid('selectRow', lastIndex);
			$('#table').datagrid('beginEdit', lastIndex);
		}
		
	function addXMPaymentWorker(obj){
			//自动提交数据
			$('#table').datagrid('acceptChanges');
			lastIndex =-1;
			$('#tableAdv').datagrid('acceptChanges');
			lastIndex1 =-1;
			addPayValue();
			//自动提交数据
			var xm_id =jQuery("#xm_id").val();	
			var xm_name=jQuery("#xm_name").val();	
			var xm_code=jQuery("#xm_code").val();
			
			var remark=encodeURIComponent(jQuery('#remark').val());
			if(!checkNullOREmpty(xm_id,'项目为必填项')){return;}
			var pay_to_id = $("#worker").combogrid("getValue");
			var pay_to_name =encodeURIComponent( $("#worker").combogrid("getText"));
			if(!checkNullOREmpty(pay_to_id,'施工单位为必填项')){return;}	
			//if(parseFloat(pay_value)==0)
			//{
			//$.messager.alert('提示','支付总额不能为0！');
			//return;
			//}
			var gds="";
			var advs="";
			var cut_payment=0;
			var jsondataAdv=$("#tableAdv").datagrid("getData");
			for(var i=0;i<jsondataAdv.total;i++){
				if(advs!=""){
					advs+=";";
				}
				advs+=jsonToStr(jsondataAdv.rows[i]);
				var index = $("#tableAdv").datagrid("getRowIndex",jsondataAdv.rows[i])+1;
				cut_payment+=parseFloat(jsondataAdv.rows[i].yet_money);
				if(parseFloat(jsondataAdv.rows[i].now_on_money)+parseFloat(jsondataAdv.rows[i].lxMoney)<parseFloat(jsondataAdv.rows[i].yet_money)){
					$.messager.alert("提示","扣垫款金额不能大于本金+利息的总额！");
					return ;
				}
				
			}
			var loan_money=jQuery("#loan_money").numberbox("getValue");
			var payValue=jQuery("#payValue").numberbox("getValue");

			var pay_value=jQuery("#pay_value").numberbox("getValue");
			//var has_receivable=jQuery("#has_receivable").numberbox("getValue");


			var jsondata=$("#table").datagrid("getData");
			for(var i=0;i<jsondata.total;i++){
				if(gds!=""){
					gds+=";";
				}
				gds+=jsonToStr(jsondata.rows[i]);
				var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
				if(parseFloat(jsondata.rows[i].budget).toFixed(2)-parseFloat(jsondata.rows[i].now_pay).toFixed(2)>=parseFloat(jsondata.rows[i].already_pay).toFixed(2)){
					console.log(parseFloat(jsondata.rows[i].end_pay).toFixed(2)-parseFloat(jsondata.rows[i].end_now_pay).toFixed(2)+"==="+parseFloat(jsondata.rows[i].abpay).toFixed(2));
					$.messager.alert("提示","支付金额不能大于实际结算金额！");
					return ;
				}
			}
			var param = "remark="+remark+"&loan_money="+loan_money+"&payValue="+payValue
			+"&pay_value="+pay_value+"&pay_to_id="+pay_to_id+"&pay_to_name="+pay_to_name
			+"&xm_id="+xm_id+"&xm_code="+xm_code+"&xm_name="+xm_name+"&gds="+gds+"&advs="+advs+"&cut_payment="+cut_payment;
			$(obj).hide();
			$.ajax({
				type:'POST',
				<%=isAdd?"url:'"+contextPath+"/springMVC/xmFinance/addXMEndPayWorker',":"url:'"+contextPath+"/springMVC/xmFinance/updateXMEndPayWorker?id="+id+"',"%>
				data:param,
				dataType:'json',
				success:function(rtJson){
					if(rtJson.rtState == '0'){
						eval('window.opener.<%=callback%>();');
						window.close();
					}
					else{
						$.messager.alert("提示",rtJson.rtMsrg);
					}
					$(obj).show();
				}
			});
		
		}

		function  jsRate(rowData){
			var date=new Date();
	        var year = date.getFullYear();       //年
	        var month = date.getMonth() + 1;     //月
	        var day = date.getDate();            //日
			var operation_date=year+"-"+month+"-"+day;
			var dates=0;
			if(0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0))){
				dates=366;
			}else{
				dates=365;
			}
			var dateNum=0;
			var lxMoney=0;
			var oneTime=operation_date;
			var twoTime=rowData.actual_operation_date.split(" ");
			dateNum=getDays(oneTime,twoTime[0]);
			if(parseFloat(rowData.now_on_money)==0){
				lxMoney=parseFloat(rowData.money*rowData.rate*dateNum/(100*dates)).toFixed(2);//利息
			}else{
				lxMoney=parseFloat(rowData.now_on_money*rowData.rate*dateNum/(100*dates)).toFixed(2);//利息
			}
			return lxMoney;
		}
		function advancesMoney(){
			var jsondataAdv=$("#tableAdv").datagrid("getData");
			for(var i=0;i<jsondataAdv.total;i++){
				if(parseFloat(jsondataAdv.rows[i].on_money)+parseFloat(jsondataAdv.rows[i].lxMoney)<parseFloat(jsondataAdv.rows[i].yet_money)){
					$.messager.alert("提示","扣垫款金额不能大于本金+利息的总额！");
					return ;
				}
			}
		}
	</script>
	</head>
	<body>
		<div style="width: 97%;padding-left:10px">
		<form id="ff">
		<input  type="hidden" id="pay_to_id" name="pay_to_id" >
		<input  type="hidden" id="pay_to_name" name="pay_to_name" >
			<table  style="border-collapse: collapse;" width="100%" border="1px" bordercolor="#0eb83a">
				<tr>
					<td align="right" class="td1" nowrap>项目编号：</td>
					<td class="td2" nowrap>
						<input  id="xm_code" name="xm_code" readOnly value="<%=xm_code%>" placeholder="项目验收后停止进度付款">
						<input type="hidden" id="xm_id" name="xm_id" readOnly value="<%=xm_id%>">
	
					</td>
					<td align="right" class="td1" nowrap>项目名称：</td>
					<td class="td2" nowrap>
						<input  id="xm_name" name="xm_name" readOnly value="<%=xm_name%>" placeholder="项目验收后停止进度付款">
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>项目部门：</td>
					<td class="td2" nowrap>
						<input  id="dept_name" name="dept_name" readOnly value="<%=dept_name%>">
						<input  type="hidden" id="dept_id" name="dept_id" readOnly value="<%=dept_id%>">
					</td>
					<td align="right" class="td1" nowrap>经办人：</td>
					<td class="td2" nowrap>
						<input  id="person" name="person" readOnly value="<%=person%>">
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>对应客户：</td>
					<td class="td2" nowrap colspan="3">
						<input  id="customer" name="customer" readOnly value="<%=customer%>">
						<input  type="hidden" id="customer_id" name="customer_id" readOnly value="<%=customer_id%>">
					</td>
				</tr>
				<tr>
			      <td align="right" class="td1" nowrap>选择施工队：</td>
					<td class="td2" nowrap colspan="3">
						<input  id="worker" name="worker" >
					</td>	
				</tr>
			
				<tr>	
			        <td align="right" class="td1" nowrap>付款金额：</td>
					<td class="td2" nowrap colspan="3">
						<input  id="pay_value" name="pay_value" class="easyui-numberbox" data-options="min:0,precision:2" value="0">[扣垫款与支付的总和]
					</td>
				</tr>	
				</tr>	
					<tr>	
			        <td align="right" class="td1" nowrap>借款金额：</td>
					<td class="td2" nowrap    >
						<input  id="loan_money" name="loan_money" class="easyui-numberbox" data-options="min:0,precision:2" readonly="readonly" value="0">(自动计算)
					</td>
					  <td align="right" class="td1" nowrap>实际付款金额：</td>
					<td class="td2" nowrap   >
						<input  id="payValue" name="payValue" class="easyui-numberbox" data-options="min:0,precision:2" readonly="readonly" value="0">(自动计算)
					</td>
				</tr>						
				<tr>
					<td align="right" class="td1" nowrap>摘要：</td>
					<td class="td2" nowrap colspan='3'>
						<textarea  id="remark" name="remark" rows="6" style="width: 100%"></textarea>
					</td>
				</tr>
				<%if(!"1".equals(isShow)){ %>
				<tr>
					<td align="right" class="td1" nowrap></td>
					<td class="td2" nowrap colspan='3'>
						<div align="left">
						   
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="addXMPaymentWorker(this);">提交</a>
							
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:window.close();">关闭</a>
						</div>
					</td>
				</tr>
				<%} %>
				<tr>
					<td colspan="4"  nowrap>
						<div id="tableAdv"></div>
					</td>
				</tr>
				<tr>
					<td colspan="4"  nowrap>
						<div id="table"></div>
					</td>
				</tr>
			</table>
			</form>
		</div>
		
	</body>
</html>